<?php
/**
 * 视图层基类
 */
class View {

    /**
     * 缓存文件生存期
     * @var LIFE_TIME
     */
    const LIFE_TIME = 216000;
    
    /**
     * Smarty模版引擎对象
     * @var Object
     */
    protected static $smarty;

    //用于assign赋值的临时存放变量
    private static $smarty_tpl_var;
    
    /**
     * 初始化模版引擎
     * @return void
     */
    public function __construct() {}
    
    /**
     * 获取Smarty实例对象
     * @return object
     */
    public function getSmartyInstance() {
        if (self::$smarty == null) {
            mk_dir(DATA_DIR.'Compile/'.APP_NAME.'/');
            include(COM_DIR.'Smarty/Smarty.class.php');
            self::$smarty = new Smarty();
            //self::$smarty->registerPlugin('modifier', 'utf8Substr', 'utf8Substr');
            self::$smarty->registerPlugin('modifier', 'C', 'C');//系统配置参数
            self::$smarty->registerPlugin('modifier','encode', array(My::getInstance(), 'encode'));//加密
            self::$smarty->registerPlugin('modifier','decode', array(My::getInstance(), 'decode'));//解密
            self::$smarty->registerPlugin('modifier','URL', array(Router::getInstance(), 'encodeUrl'));//当开启路由时,将源生url转为静态url
            self::$smarty->registerPlugin('modifier','photo', array(My::getInstance(), 'thums'));//引用缩略图(任意尺寸)
            self::$smarty->registerPlugin('modifier','user', array(My::getInstance(), 'user'));//得到当前用户的SESSION信息
            self::$smarty->registerPlugin('function','form', array(Form::getInstance(), 'form_form'));//表单模型Form::form()
            self::$smarty->registerPlugin('modifier','unserialize', array(My::getInstance(), 'unserialize'));//解码
            self::$smarty->registerPlugin('modifier','decodeHtml', array(My::getInstance(), 'decodeHtml'));//html解码
            self::$smarty->registerPlugin('modifier','encodeHtml', array(My::getInstance(), 'encodeHtml'));//html加密
            self::$smarty->registerPlugin('modifier','getFileSize', array(File::getInstance(), 'getFileSize'));//得到文件大小函数
            self::$smarty->cache_dir = DATA_DIR.'Cache/'.APP_NAME.'/';
            self::$smarty->compile_dir = DATA_DIR.'Compile/'.APP_NAME.'/';
            self::$smarty->template_dir = APP_DIR.'View/';
            self::$smarty->left_delimiter = '{{';
            self::$smarty->right_delimiter = '}}';
            //self::$smarty->force_compile = true;//强制重新编译
            self::$smarty->debugging = false;
            self::$smarty->caching = false;
            //self::$smarty->compile_check = true; //设置为false则当模板内容改变时不会自动检测，性能影响不大，建议默认的true
            //self::$smarty->cache_lifetime = 120;  //缓存存活时间（秒）
        }
        return self::$smarty;
    }

    /**
     * assign变量赋值
     */
    public function assign($name, $value=null) {
        self::$smarty_tpl_var[$name] = $value;
    }
    /**
     *
     * 获取已assign中的值
     */
    public function getAssign($name) {
        if(isset(self::$smarty_tpl_var[$name]))
            return self::$smarty_tpl_var[$name];
        else
            return null;
    }
    
    /**
     * fetch得到模板内容
     * @return string
     */
    public function fetch($path='', $cache_id='') {
        //记录模板显示的开始时间
        T('viewStartTime');
        //得到模板路径
        $path = $this->getTplPath($path);
        //得到缓存ID
        $cacheId = self::getCacheId($path,$cache_id);
        $result = My::getCache($cacheId);
        //判断文件的最后更新时间是否相等
        $isChange = (@filemtime(APP_DIR.'View/'.$path)===My::arr2var($result,'lastUpdateTime','__null__'))?false:true;
        //缓存不存在或模板文件已经改变时
        if(!$result OR $isChange){
            //smarty初始化
            $this->getSmartyInstance();
            //变量统一赋值
            if(is_array(self::$smarty_tpl_var))
            foreach(self::$smarty_tpl_var as $key=>$value){
                self::$smarty->assign($key, $value);  
            }
            //fetch
            $result['content'] = self::$smarty->fetch($path, $cacheId);
            //记录模板最后修改的时间
            $result['lastUpdateTime'] = filemtime(APP_DIR.'View/'.$path);
            //if(C('body_filter')==true) { $content = $router->body_filter($content); }//抽出body中的css/js代码
            //值为空时,置为字符串null,否则缓存不起作用
            My::setCache($cacheId, $result);
        }
        return My::arr2var($result,'content');
    }
    /**
     * 视图层显示
     * @param string $path 模板路径
     */
    public function display($path='', $cache_id='') {
        //if(!ini_get('zlib.output_compression') && C('OUTPUT_ENCODE')) ob_start('ob_gzhandler');//对输出内容进行zlib压缩(暂时不需要了，统一用rewrite入口的压缩配置即可)
        // 网页字符编码
        header('Content-Type:text/html; charset=utf-8');
        header('Cache-control: private');  // 页面缓存控制
        header('X-Powered-By: Dreamfans');
        $content = self::fetch($path, $cache_id);
        echo $content;
    }
    /**
     * 获取模板页面路径
     * @return string
     */
    public function getTplPath($path = '') {
        return (empty($path) ? CONTROLLER_NAME.'/'.ACTION_NAME : $path) . '.html';
    }
    /**
     * 获得缓存ID
     */
    private function getCacheId($path,$cache_id=''){
        if(is_array($cache_id))
            $cache_id = md5(serialize($cache_id));
        $cache_id = $path.$cache_id;
        $cache_id .= is_array(self::$smarty_tpl_var)?md5(serialize(self::$smarty_tpl_var)):'';
        return $cache_id;
    }

}
